﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
namespace MTRC.ODMS.Web.SOM.StationCleaning
{
    /// <summary>
    /// Author :Ningheming
    /// Station Cleaning 
    /// </summary>
    public partial class StationCleaningEntry : BasePage_SOM
    {
        #region MenuID

        protected override string MenuID
        {
            get
            {
                return "M140602";
            }
        }

        #endregion       

         #region Page Init And Load
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.ChangeLanguage += new ChangeLanguageEventHandler(SetLanguage_Click);            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.TracePageChange = true;
            if (!IsPostBack)
            {
                SetLanguage();
                GetCleanPassScore();
                GetScoreTable();
                BindDataTable();
            }

            SetCleanID(); 

            if (this.ddlStation.SelectedValue.ToString() != string.Empty)
            {
                this.lblCleanScoreHeader.Text = this.ddlStation.SelectedItem.Text + " " + this.ddlYear.SelectedItem.Text + "/" + this.ddlMonth.SelectedItem.Text;
            }
            else
            {
                this.lblCleanScoreHeader.Text = this.ddlYear.SelectedItem.Text + "/" + this.ddlMonth.SelectedItem.Text;

            }            
            this.ClientScript.RegisterStartupScript(typeof(StationCleaningEntry), "OpenDepartPage", "<script language='javascript'>CheckIfAllScoreInput()</script>");
        }

        #endregion

        #region SetLanguage

        private void SetCleanID()
        {
            //--------------- Add by zengshunbo 2009-02-24 Issue:1027 ---------------

            int StationID;
            if (this.ddlStation.SelectedValue.ToString() == string.Empty)
            {
                StationID = 0;
            }
            else
            {
                StationID = int.Parse(ddlStation.SelectedValue.ToString());
            }

            DataTable dt = MTRC.ODMS.DAL.SOM.CodeSetup.CDCleanShift.GetCleanScoreByYearMonth(LangCode, this.ddlYear.SelectedValue.ToString(), this.ddlMonth.SelectedValue.ToString(), StationID);

            if (dt.Rows.Count > 0)
            {
                this.hdnCleanID.Value = int.Parse(dt.Rows[0]["CleanID"].ToString()).ToString();
            }

            //--------------- End add by zengshunbo 2009-02-24 Issue:1027---------------
        }


        void SetLanguage_Click(object sender, EventArgs e)
        {
            SetLanguage();
            GetScoreTable();
            BindDataTable();
        }

        private void GetCleanPassScore()
        {
            int StationID;
            if (this.ddlStation.SelectedValue.ToString() == string.Empty)
            {
                StationID = 0;
            }
            else
            {
                StationID = int.Parse(ddlStation.SelectedValue.ToString());
            }

            DataTable dt = DAL.SOM.CodeSetup.CDCleanShift.GetPassScoreByStationID(StationID);
            if (dt.Rows.Count > 0)
            {
                this.hdnCleanPassScore.Value = dt.Rows[0]["PassScore"].ToString();
            }
            else
            {
                this.hdnCleanPassScore.Value = "60";
            }
        }

        private void SetLanguage()
        {

            this.lblYearMonth.Text = this.GetLabel("SOM_YearMonth", true);
            this.btnSave.Text = this.GetLabel("COM_Save");
            this.btnPrint.Text = this.GetLabel("COM_Print");
            this.btnSearch.Text = this.GetLabel("COM_Search");
            this.lblStation.Text = this.GetLabel("SOM_Station", true);
            this.lblComments.Text = this.GetLabel("COM_GerneralComments");
            this.lblShift.Text = this.GetLabel("SOM_Shift");
            this.lblGerneralComments.Text = this.GetLabel("COM_GerneralComments");
            this.lblFault.Text = this.GetLabel("SOM_FaultDays", true);
            this.lblLeave.Text = this.GetLabel("SOM_InjurySickLeave", true);
            this.lblStationAverage.Text = this.GetLabel("SOM_StationAverage", true);
            this.lblReasonLowerStanderdHeader.Text = this.GetLabel("SOM_LowerStandardReason");
            this.lblShiftHeader.Text = this.GetLabel("SOM_Shift");
            this.lblSubStanderdActionHeader.Text = this.GetLabel("SOM_SubStandardAction");
            this.lblWeekNoHeader.Text = this.GetLabel("SOM_WeekNo");
            this.lblScoreHeader.Text = this.GetLabel("SOM_CleanScore");
            this.LowerStandard.Text = this.GetLabel("SOM_LowerStandard");
            this.btnExportCurrentStationData.Text = this.GetLabel("SOM_StationCleaningExportCurrentData"); //Add by zengshunbo issue:1059 2009-03-06
            this.btnExportAllStationData.Text = this.GetLabel("SOM_StationCleaningExportAllData");//Add by zengshunbo issue:1059 2009-03-06
            this.hdnSaveCheckCommentsMeg.Value = this.GetMessage("SOM_StationCleanShiftCommentsCheck", this.LangCode); //Add by zengshunbo2009-02-27 TD:1224
            this.txtFaultDay.Text = "0";
            this.txtLeave.Text = "0";
            this.NumericUpDownExtender1.Minimum = 0;
            this.NumericUpDownExtender1.Maximum = 200;
            this.NumericUpDownExtender2.Minimum = 0;
            this.NumericUpDownExtender2.Maximum = 500;
            this.hdnErrorMessageSave.Value = this.GetLabel("SOM_ReasonAndActionNeedInput");
            txtFaultDay.Attributes.Add("onkeydown", "KeyDown(this)");
            txtLeave.Attributes.Add("onkeydown", "KeyDown(this)");

            BindDataDll();
            if (this.ddlStation.SelectedValue.ToString() != string.Empty)
            {
                this.lblCleanScoreHeader.Text = this.ddlStation.SelectedItem.Text + " " + this.ddlYear.SelectedItem.Text + "/" + this.ddlMonth.SelectedItem.Text;
            }
            else
            {
                this.lblCleanScoreHeader.Text = this.ddlYear.SelectedItem.Text + "/" + this.ddlMonth.SelectedItem.Text;
            }

        }

        private void BindDataDll()
        {
            //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode)), false);
            BindStation();
            BindListControl(this.ddlYear, "Year", "Year", DAL.SOM.CodeSetup.CDCleanShift.GetCleanYear(this.LangCode), false);
            BindListControl(this.ddlMonth, "MonthNum", "Description", DAL.SOM.CodeSetup.CDCleanShift.GetCleanMonthDesc(this.LangCode ,this.Version .ToString ()), false);
            DateTime dtbNow = DAL.COM.Util.GetCurrentSystemTime();
            string Year = dtbNow.Year.ToString ().Trim();
            string Month = dtbNow.Month.ToString();
            this.FindByValueAndSelect(ddlYear, Year);
            this.FindByValueAndSelect(ddlMonth, Month);
            //update by gordon 20151020 U247 | Can not Test
            //if (ddlStation.Items.FindByValue(this.ODMUser.StationID.ToString()) != null)
            //{
            //    this.FindByValueAndSelect(ddlStation, this.ODMUser.StationID.ToString());
            //}
            if (ddlStation.Items.FindByValue(this.ODMUser.LocationID.ToString()) != null)
            {
                this.FindByValueAndSelect(ddlStation, this.ODMUser.LocationID.ToString());
            }
            //if (!DAL.Security.User.CanFunctionItemAccess("M140602_F2", this.ODMUser.UserProfileID, this.MenuID))
            //{
                
            //    ddlStation.Enabled = false;            
            //}

        }

        private void BindStation()
        {
            if (DAL.Security.User.CanFunctionItemAccess("M140602_F2", this.ODMUser.UserProfileID, this.MenuID))//access all station.
            {
                //update by gordon 20151021 U247 | Can not test
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode),this.ODMUser .StationID), false);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.LocationID), false);

                this.btnExportAllStationData.Enabled = true; //Add by zengshunbo issue:1059 2009-03-06
            }
            else if (DAL.Security.User.CanFunctionItemAccess("M140602_F3", this.ODMUser.UserProfileID, this.MenuID))//Can Access other stations.
            {
                //BindStation
                //update by gordon 20151021 U247 | Can not test
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode),this.ODMUser .StationID), false);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), false);
            }
            else
            {
                //update by gordon 20151021 U247 | Can not test
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode),this.ODMUser .StationID), false);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), false);
                this.ddlStation.Enabled = false;
                this.btnExportAllStationData.Enabled = false; //Add by zengshunbo issue:1059 2009-03-06
            }

            //------------------------ Add by zengshunbo issue:1059 2009-03-06 --------------------------
            
            if (DAL.Security.User.CanFunctionItemAccess("M140602_F4", this.ODMUser.UserProfileID, this.MenuID))
            {
                this.btnExportCurrentStationData.Enabled = true;
            }
            else
            {
                this.btnExportCurrentStationData.Enabled = false;
            }

            //------------------------ End add by zengshunbo issue:1059 2009-03-06 --------------------------
          
        }

        #endregion

        /// <summary>
        /// Get Cleaning Score Table 
        /// </summary>
        private void GetScoreTable()
        {
            Hashtable hTable = GetHashTableData(hdnValues.Value.ToString());
            int StationID;
            if (this.ddlStation.SelectedValue.ToString() == string.Empty)
            {
                StationID = 0;
            }
            else
            {
                StationID = int.Parse(ddlStation.SelectedValue.ToString());
            }

            DataTable dt = MTRC.ODMS.DAL.SOM.CodeSetup.CDCleanShift.GetCleanScoreByYearMonth(this.LangCode, this.ddlYear.SelectedValue.ToString(), this.ddlMonth.SelectedValue.ToString(), StationID);//get weekno,shift,and score
            DataTable dtToday = MTRC.ODMS.DAL.SOM.CodeSetup.CDCleanShift.WeekNoToady(DAL.COM.Util.GetCurrentSystemTime().Date); //get weekno today lays on

            //huangyao 20081003 // do not access DB in For loop
            bool isReadOnly = false;
            if (DAL.Security.User.CanFunctionItemAccess("M140602_F1", this.ODMUser.UserProfileID, this.MenuID))
            {
                isReadOnly = true;
                this.txtLeave.Enabled = false;
                this.NumericUpDownExtender1.Enabled = false;
                this.txtFaultDay.Enabled = false;
                this.NumericUpDownExtender2.Enabled = false;

                //--------------Add by zengshunbo 2009-03-18 issue:1102-------------
                this.btnLeaveDown.Disabled = true;
                this.btnLeaveUp.Disabled = true;
                this.btnFaultDayDown.Disabled = true;
                this.btnFaultDayUp.Disabled = true;
                //--------------End Add by zengshunbo 2009-03-18 issue:1102-------------
            }
            //-----------------------------
            this.hdnControlArrowStatus.Value = "false";//Added by jensen 2008-12-18
            if (dt.Rows.Count > 0)
            {
                DataTable dtDays = DAL.SOM.CodeSetup.CDCleanShift.GetNoOfLeaveAndMachineFault(int.Parse(dt.Rows[0]["CleanID"].ToString()));
                if (dtDays.Rows.Count > 0)
                {
                    this.txtLeave.Text = dtDays.Rows[0]["Leave"].ToString();
                    this.txtFaultDay.Text = dtDays.Rows[0]["Fault"].ToString();

                    //------------------------- Add by zengshunbo issue:1102  2009-03-17 ---------------------

                    this.hdnFaultDay.Value = dtDays.Rows[0]["Fault"].ToString();
                    this.hdnLeave.Value = dtDays.Rows[0]["Leave"].ToString();

                    //------------------------- End add by zengshunbo issue:1102  2009-03-17 ---------------------

                    hdnLastUpdTime.Value = this.FormatDateTime(Convert.ToDateTime(dtDays.Rows[0]["LastUpdTime"].ToString()), true, true);
                }
                else
                {
                    this.txtLeave.Text = "0";
                    this.txtFaultDay.Text = "0";
                    
                    this.NumericUpDownExtender1.Minimum = 0; //add by zengshunbo 2009-03-23
                    this.NumericUpDownExtender2.Minimum = 0; //add by zengshunbo 2009-03-23                    
                    this.hdnLeave.Value = "0";  //add by zengshunbo 2009-03-23
                    this.hdnFaultDay.Value = "0";   //add by zengshunbo 2009-03-23

                    hdnLastUpdTime.Value = string.Empty;
                }
            
                float SumStationScore = 0;
                int   NumStationScore = 0;

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (i == 0)
                    {
                        TableRow tr0 = new TableRow();
                        tr0.Attributes.Add("class", "Title1");
                        for (int j = 0; j < 7; j++)   //field C+[j] is weekno
                        {
                            if (j == 0)
                            {
                                TableCell td = new TableCell();
                                Label label = new Label();
                                td.Attributes.Add("class", "TdShiftStyle");
                                label.ID = dt.Rows[0]["ShiftID"].ToString() + i.ToString() + "shift";
                                label.Text = this.GetLabel("SOM_CleanScore");   //header
                                td.Controls.Add(label);
                                tr0.Cells.Add(td);
                            }
                            else if (dt.Rows[0]["C" + j].ToString() != string.Empty)
                            {
                                TableCell td = new TableCell();
                                Label label = new Label();                        //the score have input and can not be editted
                                td.Attributes.Add("class", "TdStyle");
                                label.ID = dt.Rows[0]["ShiftID"].ToString() + dt.Rows[0]["C" + j].ToString() + "shift2";

                                //----------------------------- Modify by zengshunbo 2009-02-26 issue:1026 ---------------------------

                                //Del:
                                //label.Text = dt.Rows[0]["C" + j].ToString();


                                //Add:
                                if (this.LangCode == "1")
                                {
                                    label.Text = dt.Rows[0]["C" + j].ToString();
                                }
                                else
                                {
                                    label.Text = string.Format(this.GetLabel("SOM_YearWeekNo"), dt.Rows[0]["C" + j].ToString().Substring(0, 4), dt.Rows[0]["C" + j].ToString().Substring(4)); //Merge Stockholm&HK to BJL4-----
                                }

                                //----------------------------- End modify by zengshunbo 2009-02-26 issue:1026 ---------------------------

                                td.Controls.Add(label);
                                tr0.Cells.Add(td);

                            }
                        }

                        TableCell tdAvg = new TableCell();
                        tdAvg.Attributes.Add("style", "text-align:right;");
                        Label lblAvg = new Label();
                        lblAvg.ID = dt.Rows[i]["ShiftID"].ToString() + "Avg";
                        lblAvg.Text = this.GetLabel("SOM_AverageScore");  //calculate the average score this shift
                        tdAvg.Controls.Add(lblAvg);
                        tr0.Cells.Add(tdAvg);
                        CrTable.Rows.Add(tr0);
                    }
                    else
                    {
                        TableRow tr0 = new TableRow();
                        for (int j = 0; j < 7; j++)
                        {
                            if (j == 0)
                            {
                                TableCell td = new TableCell();
                                Label label = new Label();
                                //label.Attributes.Add("class","Title1");
                                label.ID = dt.Rows[i]["ShiftID"].ToString() + "2333";
                                label.Text = dt.Rows[i]["Shift"].ToString();   // shift description
                                td.Controls.Add(label); 
                                //td.Attributes.Add("style", "width:70px;");
                                tr0.Cells.Add(td);
                            }
                            else if (dt.Rows[i]["C" + j].ToString() != string.Empty)
                            {
                                TableCell td = new TableCell();
                                td.Attributes.Add("class", "TdStyle");
                                Label label = new Label();
                                label.ID = dt.Rows[i]["ShiftID"].ToString() + dt.Rows[0]["C" + j].ToString();
                                label.Text = dt.Rows[i]["C" + j].ToString();
                                td.Controls.Add(label);
                                tr0.Cells.Add(td);
                            }
                            else if (dt.Rows[i]["C" + j].ToString() == string.Empty && dt.Rows[0]["C" + j].ToString() != string.Empty)
                            {
                                TableCell td = new TableCell();
                                td.Attributes.Add("class", "TdStyle");
                                TextBox label = new TextBox();              //have not marked can be editted generate a textbox

                                label.ID = dt.Rows[i]["ShiftID"].ToString() + dt.Rows[0]["C" + j].ToString();
                                label.Text = "0";
                                DateTime dtNow = DAL.COM.Util.GetCurrentSystemTime();
                                int SelectedYear = int.Parse(this.ddlYear.SelectedValue.ToString());
                                int SelectedMonth = int.Parse(this.ddlMonth.SelectedValue.ToString());
                                if (SelectedYear > dtNow.Year || (SelectedYear == dtNow.Year && SelectedMonth > dtNow.Month))
                                {
                                    label.Enabled = false;
                                }   

                                if (dtToday.Rows.Count > 0)
                                {
                                    if (int.Parse(dt.Rows[0]["C" + j].ToString()) > int.Parse(dtToday.Rows[0]["WeekNo"].ToString()))
                                    {
                                        label.Enabled = false;
                                    }
                                }   //further date can not be marked

                                //if (DAL.Security.User.CanFunctionItemAccess("M140602_F1", this.ODMUser.UserProfileID, this.MenuID))
                                if(isReadOnly)  //huangyao 20081003 // do not access DB in For loop
                                {
                                    label.Enabled = false;
                                }
                                //if have no access limit ,can not be editted
                                label.Attributes.Add("onchange", "CheckScore(this);");//check score 
                                //label.Attributes.Add("onkeydown", "KeyDown(this)"); //huangyao 20090205
                                //label.Attributes.Add("onkeydown", @"value=value.replace(/[^\d]/g,'');"); //huangyao 20090205
                                label.Attributes.Add("onkeydown", "KeyDown(this);"); //Add by zengshunbo 2009-02-27 issue1041
                                td.Controls.Add(label);
                                tr0.Cells.Add(td);
                                if (hTable.ContainsKey(dt.Rows[i]["ShiftID"].ToString() + dt.Rows[0]["C" + j].ToString()))
                                {
                                    label.Text = hTable[dt.Rows[i]["ShiftID"].ToString() + dt.Rows[0]["C" + j].ToString()].ToString();

                                }
                                if (this.hdnControlArrowStatus.Value == "false" && label.Enabled)//Added by jensen 2008-12-18
                                {
                                    this.hdnControlArrowStatus.Value = "true";
                                }
                            }
                        }

                        float SumScore = 0;
                        int NumScore = 0;

                        TableCell tdAvg = new TableCell();
                        tdAvg.Attributes.Add("style", "text-align:right");
                        Label lblAvg = new Label();
                        lblAvg.ID = dt.Rows[i]["ShiftID"].ToString() + "Avg";
                        for (int k = 1; k <= 6; k++)
                        {
                            if (dt.Rows[i]["C" + k].ToString() != string.Empty)
                            {
                                NumScore = NumScore + 1;
                                SumScore = SumScore + float.Parse(dt.Rows[i]["C" + k].ToString());
                            }
                        }
                        if (NumScore == 0)
                        {
                            lblAvg.Text = "0";

                        }
                        else
                        {
                            lblAvg.Text = Math.Round(SumScore / NumScore, 2).ToString();
                            NumStationScore = NumStationScore + 1;
                            SumStationScore = SumStationScore + (float)Math.Round(SumScore / NumScore, 2);
                        }
                        tdAvg.Controls.Add(lblAvg);
                        tr0.Cells.Add(tdAvg);
                        CrTable.Rows.Add(tr0);
                    }
                }
               
                if (NumStationScore == 0||NumStationScore!=(dt.Rows.Count -1))
                {
                    this.lblStationAverageInfo.Text = "";
                }
                else
                {

                    this.lblStationAverageInfo.Text = Math.Round(SumStationScore / NumStationScore, 2).ToString();
                }//calculate station average score

                //Add by jensen 2008-12-18
                if (DAL.Security.User.CanFunctionItemAccess("M140602_F1", this.ODMUser.UserProfileID, this.MenuID))
                {
                    this.txtLeave.Enabled = false;
                    this.NumericUpDownExtender1.Enabled = false;
                    this.txtFaultDay.Enabled = false;
                    this.NumericUpDownExtender2.Enabled = false;
                    btnSave.Enabled = false;

                    //--------------Add by zengshunbo 2009-03-18 issue:1102-------------
                    this.btnLeaveDown.Disabled = true;
                    this.btnLeaveUp.Disabled = true;
                    this.btnFaultDayDown.Disabled = true;
                    this.btnFaultDayUp.Disabled = true;
                    //--------------End Add by zengshunbo 2009-03-18 issue:1102-------------
                }
                else
                {
                    this.NumericUpDownExtender1.Enabled = true;

                    //--------------Add by zengshunbo 2009-03-18 issue:1102-------------
                    this.btnLeaveDown.Disabled = false;
                    this.btnLeaveUp.Disabled = false;
                    this.btnFaultDayDown.Disabled = false;
                    this.btnFaultDayUp.Disabled = false;
                    //--------------End Add by zengshunbo 2009-03-18 issue:1102-------------
                    
                    //--------------- Add by HuangYao Issue:1102 2009-03-17---------------
                    //if (txtLeave.Text.Trim() != string.Empty)
                    //{
                    //    this.NumericUpDownExtender1.Minimum = int.Parse(txtLeave.Text.Trim());
                    //}
                    //if (txtFaultDay.Text.Trim() != string.Empty)
                    //{
                    //    this.NumericUpDownExtender2.Minimum = int.Parse(txtFaultDay.Text.Trim());
                    //}
                    //--------------- End add by HuangYao Issue:1102 2009-03-17---------------


                    this.NumericUpDownExtender2.Enabled = true;
                    this.txtLeave.Enabled = true;
                    this.txtFaultDay.Enabled = true;
                    btnSave.Enabled = true;
                    if (this.hdnControlArrowStatus.Value == "false")
                    {
                        this.txtLeave.Enabled = false;
                        this.txtFaultDay.Enabled = false;
                        this.NumericUpDownExtender1.Enabled = false;
                        this.NumericUpDownExtender2.Enabled = false;

                        //--------------Add by zengshunbo 2009-03-18 issue:1102-------------
                        this.btnLeaveDown.Disabled = true;
                        this.btnLeaveUp.Disabled = true;
                        this.btnFaultDayDown.Disabled = true;
                        this.btnFaultDayUp.Disabled = true;
                        //--------------End Add by zengshunbo 2009-03-18 issue:1102-------------

                        btnSave.Enabled = false;
                    }
                   
                }
                //Add by jensen 2008-12-18 end
            }
          
        }

        /// <summary>
        /// If the score less than the passscore ,it must be input less standard reason and action
        /// </summary>
        protected void AddRows()
        {
            Hashtable hTable = GetHashTableData(hdnValues.Value.ToString());

            int StationID;
            if (this.ddlStation.SelectedValue.ToString() == string.Empty)
            {
                StationID = 0;
            }
            else
            {
                StationID = int.Parse(ddlStation.SelectedValue.ToString());
            }
            DataTable dt = MTRC.ODMS.DAL.SOM.CodeSetup.CDCleanShift.GetCleanScoreByYearMonth(this.LangCode, this.ddlYear.SelectedValue.ToString(), this.ddlMonth.SelectedValue.ToString(), StationID);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 1; j < 7; j++)
                    {
                        if (hTable.ContainsKey(dt.Rows[i]["ShiftID"].ToString() + dt.Rows[0]["C" + j].ToString()))
                        {
                            int Score = int.Parse(hTable[dt.Rows[i]["ShiftID"].ToString() + dt.Rows[0]["C" + j].ToString()].ToString());
                            string ScoreShiftWeekNo = dt.Rows[i]["ShiftID"].ToString() + dt.Rows[0]["C" + j].ToString();
                            if (Score > 0 && Score < int.Parse(this.hdnCleanPassScore.Value.ToString()))
                            {
                                TableRow tr = new TableRow();
                                TableCell tdLowerStanderdWeekNo = new TableCell();
                                Label lblLowerStanderdWeekNo = new Label();
                                lblLowerStanderdWeekNo.Text = ScoreShiftWeekNo.Trim().Substring(1, 6).ToString();
                                tr.Cells.Add(tdLowerStanderdWeekNo);
                                tdLowerStanderdWeekNo.Controls.Add(lblLowerStanderdWeekNo);
                                TableCell tdLowerStanderdShift = new TableCell();
                                Label lblLowerStanderdShift = new Label();
                                DataTable dtCleanShift = DAL.SOM.CodeSetup.CDCleanShift.GetShift(this.LangCode, int.Parse(dt.Rows[i]["ShiftID"].ToString()), 1);
                                lblLowerStanderdShift.Text = dtCleanShift.Rows[0]["ShiftCode"].ToString();
                                tdLowerStanderdShift.Controls.Add(lblLowerStanderdShift);
                                tr.Cells.Add(tdLowerStanderdShift);
                                TableCell tdLowerStanderdScore = new TableCell();
                                Label lblLowerStanderdScore = new Label();
                                lblLowerStanderdScore.Text = Score.ToString();
                                tdLowerStanderdScore.Controls.Add(lblLowerStanderdScore);
                                tr.Cells.Add(tdLowerStanderdScore);
                                TableCell tdLowerStanderdReason = new TableCell();
                                TextBox txtLowerStanderReason = new TextBox();
                                txtLowerStanderReason.TextMode = TextBoxMode.MultiLine;
                                txtLowerStanderReason.Attributes.Add("style", "width:100%");
                                txtLowerStanderReason.Attributes.Add("onchange", "CheckLowerStandardReason(this);");
                                //txtLowerStanderReason.Attributes.Add("onfocus", "SetFocus(this);");
                                txtLowerStanderReason.ID = "txt" + ScoreShiftWeekNo.Trim();
                                tdLowerStanderdReason.Controls.Add(txtLowerStanderReason);
                                tr.Cells.Add(tdLowerStanderdReason);
                                TableCell tdSunStanderdAction = new TableCell();
                                TextBox txtSunStanderdAction = new TextBox();
                                txtSunStanderdAction.TextMode = TextBoxMode.MultiLine;
                                txtSunStanderdAction.Attributes.Add("style", "width:100%");
                                txtSunStanderdAction.Attributes.Add("onchange", "CheckLowerStandardAction(this);");
                                txtSunStanderdAction.ID = "txtSub" + ScoreShiftWeekNo.Trim();
                                tdSunStanderdAction.Controls.Add(txtSunStanderdAction);
                                tr.Cells.Add(tdSunStanderdAction);
                                tblLowerStanderd.Rows.Add(tr);
                            }
                        }
                    }
                }
            }
        }       

        protected void BindDataTable()
        {
            int StationID;
            if (this.ddlStation.SelectedValue.ToString() == string.Empty)
            {
                StationID = 0;
            }
            else
            {
                StationID = int.Parse(ddlStation.SelectedValue.ToString());
            }

            DataTable dt = MTRC.ODMS.DAL.SOM.CodeSetup.CDCleanShift.GetCleanScoreByYearMonth(this.LangCode, this.ddlYear.SelectedValue.ToString(), this.ddlMonth.SelectedValue.ToString(), StationID);
            if (dt.Rows.Count > 0)
            {
                int CleanID = 0;
                if (dt.Rows[0]["CleanID"].ToString() != string.Empty)
                {
                    CleanID = int.Parse(dt.Rows[0]["CleanID"].ToString());
                }
                Hashtable hCommentTable = GetHashTableData(this.hdnCleanShiftComments.Value.ToString());

                DataSet dsComment = DAL.SOM.CodeSetup.CDCleanShift.GetCleanComments(CleanID, this.LangCode, this.Version.ToString());
                DataTable dtComment = dsComment.Tables[0];
                hdnCommentUpdTempId.Value = BLL.SOM.TempData.CacheDataSet(dsComment, this.ODMUser.ID, this.ODMUser.Domain.ToString()).ToString();
                if (dtComment.Rows.Count > 0)//display comments
                {
                    //huangyao 20081003 // do not access DB in For loop
                    bool isReadOnly = false;
                    if (DAL.Security.User.CanFunctionItemAccess("M140602_F1", this.ODMUser.UserProfileID, this.MenuID))
                    {
                        isReadOnly = true;
                    }
                    //--------------------------------------

                    for (int i = 0; i < dtComment.Rows.Count; i++)
                    {
                        if (dtComment.Rows[i]["CleanShiftID"].ToString() != string.Empty)
                        {

                            DateTime daynow = DAL.COM.Util.GetCurrentSystemTime();
                            TableRow tr = new TableRow();
                            TableCell tdShift = new TableCell();
                            tdShift.Attributes.Add("style", "width:60px;");
                            Label lblShift = new Label();
                            lblShift.Text = dtComment.Rows[i]["Shift"].ToString();
                            lblShift.ID = "lbl" + dtComment.Rows[i]["CleanID"].ToString() + dtComment.Rows[i]["CleanShiftID"];
                            tdShift.Controls.Add(lblShift);
                            tr.Cells.Add(tdShift);
                            TableCell tdComments = new TableCell();
                            TextBox txtComments = new TextBox();
                            txtComments.Attributes.Add("onchange", "CheckCleanShiftComments(this);");
                            //txtComments.Attributes.Add("onload", "CheckIfAllScoreInput(this)");
                            txtComments.TextMode = TextBoxMode.MultiLine;
                            if ((int.Parse(ddlYear.SelectedValue.ToString()) > daynow.Year && int.Parse(ddlMonth.SelectedValue.ToString()) > daynow.Month) || int.Parse(ddlYear.SelectedValue.ToString()) == daynow.Year && int.Parse(ddlMonth.SelectedValue.ToString()) > daynow.Month)
                            {
                                txtComments.Enabled = false;
                                this.btnSave.Enabled = false;
                            }

                            //if (DAL.Security.User.CanFunctionItemAccess("M140602_F1", this.ODMUser.UserProfileID, this.MenuID))
                            //huangyao 20081003 // do not access DB in For loop
                            if(isReadOnly)
                            {
                                txtComments.Enabled = false;
                                this.btnSave.Enabled = false;
                            }
                            txtComments.Attributes.Add("style", "width:100%");
                            txtComments.ID = "txtComments" + dtComment.Rows[i]["CleanShiftID"].ToString();

                            if (hCommentTable.ContainsKey("txtComments" + dtComment.Rows[i]["CleanShiftID"].ToString().Trim()) && hCommentTable["txtComments" + dtComment.Rows[i]["CleanShiftID"].ToString().Trim()].ToString() != string.Empty)
                            {
                                txtComments.Text = hCommentTable["txtComments" + dtComment.Rows[i]["CleanShiftID"].ToString()].ToString();
                            }
                            else if (dtComment.Rows[i]["Comments"].ToString() != string.Empty)
                            {
                                txtComments.Text = dtComment.Rows[i]["Comments"].ToString();
                            }

                            //huangyao 20090323-----dynamic set text box rows----------begin
                            string[] slist = System.Text.RegularExpressions.Regex.Split(txtComments.Text, @"\r\n");
                            txtComments.Rows = slist.Length;
                            foreach (string tempStr in slist)
                            {
                                if (tempStr.Length > 120)
                                {
                                    txtComments.Rows = txtComments.Rows + 1;
                                }
                            }
                            if (txtComments.Rows < 2)
                            {
                                txtComments.Rows = 2;
                            }
                            //huangyao 20090323-----dynamic set text box rows----------end

                            tdComments.Controls.Add(txtComments);
                            tr.Cells.Add(tdComments);
                            tblComments.Rows.Add(tr);
                        }
                    }
                }

                int j = 0;
                DataTable dtLowStandard = DAL.SOM.CodeSetup.CDCleanShift.GetCleanBelowStandardReason(this.LangCode, CleanID);  //Just Have Saved In DataBase
                //DataSet dsLowStandard = new DataSet();
                //dsLowStandard.Tables.Add(dtLowStandard);
                //hdnLowStandardUpdTempId.Value = BLL.SOM.TempData.CacheDataSet(dsLowStandard, this.ODMUser.ID, this.ODMUser.Domain.ToString()).ToString();
                if (dtLowStandard.Rows.Count>0)//display existed reason and action
                {
                    while (j < dtLowStandard.Rows.Count)
                    {
                        TableRow tr = new TableRow();
                        tr.Attributes.Add("style", "border-width:1px;");
                        TableCell tdWeekNo = new TableCell();
                        Label lblWeekNo = new Label();
                        lblWeekNo.Text = dtLowStandard.Rows[j]["WEEK_NO"].ToString();
                        tdWeekNo.Controls.Add(lblWeekNo);
                        tr.Cells.Add(tdWeekNo);
                        TableCell tdShift = new TableCell();
                        Label lblShift = new Label();
                        lblShift.Text = dtLowStandard.Rows[j]["Shift"].ToString();
                        tdShift.Controls.Add(lblShift);
                        tr.Cells.Add(tdShift);
                        TableCell tdScore = new TableCell();
                        Label lblScore = new Label();
                        lblScore.Text = dtLowStandard.Rows[j]["CleaningScore"].ToString();
                        tdScore.Controls.Add(lblScore);
                        tr.Cells.Add(tdScore);
                        TableCell tdReason = new TableCell();
                        Label lblReason = new Label();
                        lblReason.Text = dtLowStandard.Rows[j]["SubstandardCause"].ToString();
                        tdReason.Controls.Add(lblReason);
                        tr.Cells.Add(tdReason);
                        TableCell tdAction = new TableCell();
                        Label lblAction = new Label();
                        lblAction.Text = dtLowStandard.Rows[j]["SubstandardAction"].ToString();
                        tdAction.Controls.Add(lblAction);
                        tr.Cells.Add(tdAction);
                        tblLowerStanderd.Rows.Add(tr);
                        j++;
                    }
                }
            }
        
        
        }
        /// <summary>
        /// Create Hash Table ,Save temp data,then click Save to save to database
        /// </summary>
        /// <param name="strHiddenValue"></param>
        /// <returns></returns>
        protected Hashtable GetHashTableData(string strHiddenValue)
        {            
            Hashtable hTable = new Hashtable();
            if (strHiddenValue.Trim().Length > 1)
            {
                string[] strArray = strHiddenValue.Split('§');
                
                foreach (string strItem in strArray)
                {
                    string[] strIDAndValue = strItem.Split('¶');

                    if (hTable.ContainsKey(strIDAndValue[0]))
                    {
                        hTable[strIDAndValue[0]] = strIDAndValue[1];
                    }
                    else
                    {
                        if (strIDAndValue[0].Trim().Length > 0)
                        {
                            hTable.Add(strIDAndValue[0], strIDAndValue[1]);
                        }
                    }
                }
            }
            return hTable;  
        }

        /// <summary>
        /// check whether other updataed or no any other updataed this
        /// </summary>
        /// <param name="StationID"></param>
        /// <returns>false:be ohter updataed,this can't updata; true:no one update,this can be updataed</returns>
        private bool CheckUpdataByOther(DataTable BaseSource, Hashtable ChangeSource)
        {
            for (int i = 0; i < BaseSource.Rows.Count; i++)
            {
                for (int j = 1; j < 7; j++)
                {
                    if (ChangeSource.ContainsKey(BaseSource.Rows[i]["ShiftID"].ToString() + BaseSource.Rows[0]["C" + j].ToString()) && BaseSource.Rows[i]["C" + j].ToString() != "")
                    {
                        return false;
                    }
                }
            }
            DataTable dtDays = DAL.SOM.CodeSetup.CDCleanShift.GetNoOfLeaveAndMachineFault(int.Parse(BaseSource.Rows[0]["CleanID"].ToString()));
            if (dtDays.Rows.Count > 0 && hdnLastUpdTime.Value.Trim().ToString() != this.FormatDateTime(Convert.ToDateTime(dtDays.Rows[0]["LastUpdTime"].ToString()), true, true).ToString())
            {
                return false;
            }
            DataTable dtCommentTemp = BLL.SOM.TempData.GetCacheData(int.Parse(this.hdnCommentUpdTempId.Value)).Tables[0];
            int CleanID = 0;
            if (BaseSource.Rows.Count > 0)
            {
                CleanID = int.Parse(BaseSource.Rows[0]["CleanID"].ToString());
            }
            DataTable dtComment = DAL.SOM.CodeSetup.CDCleanShift.GetCleanComments(CleanID, this.LangCode, this.Version.ToString()).Tables[0];
            DataView dvComment = new DataView();
            dvComment.Table = dtComment;
            DataTable dtResult = new DataTable();
            for (int i = 0; i < dtCommentTemp.Rows.Count; i++)
            {
                dvComment.RowFilter = "CleanID='" + dtCommentTemp.Rows[i]["CleanID"].ToString() + "' and CleanShiftID='" + dtCommentTemp.Rows[i]["CleanShiftID"].ToString() + "' and Shift='" + dtCommentTemp.Rows[i]["Shift"].ToString() + "' and Order='" + dtCommentTemp.Rows[i]["Order"].ToString() + "'";
                dtResult = dvComment.ToTable();
                if (dtResult.Rows.Count > 0 && dtCommentTemp.Rows[i]["LastUpdTime"].ToString() != dtResult.Rows[0]["LastUpdTime"].ToString())
                {
                    return false;
                }
            }
            //DataTable dtLowStandard = BLL.SOM.TempData.GetCacheData(int.Parse(this.hdnLowStandardUpdTempId.Value)).Tables[0];
            //Hashtable hLowerReasonTable = GetHashTableData(hdnLowerthanStandardReason.Value.ToString());
            //Hashtable hLowerActionTable = GetHashTableData(this.hdnLowerthanStandardAction.Value.ToString()); 
            return true;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {         
            //#region  Update Clean Comments
            //this.btnSave.Attributes.Add("onclick", "return CheckReasonAndActionInput();"); //Modify by zengshunbo 20090225 issue1027
            //int NewCleanID = 0;

            #region  Save Clean Score Data
            int StationID;
            if (this.ddlStation.SelectedValue.ToString() == string.Empty)
            {
                StationID = 0;
            }
            else
            {
                StationID = int.Parse(ddlStation.SelectedValue.ToString());
            }
            if (!DAL.SOM.Event.StationEventDa.IsLegalStation(StationID))//Gordon:Can not Test U247 20151019
            {
                //this.Alert("Current station is not an legal station for SOM");
                this.Alert(this.GetMessage("SOM_LegalStationCheck"));
                return;
            }
            DataTable dt = MTRC.ODMS.DAL.SOM.CodeSetup.CDCleanShift.GetCleanScoreByYearMonth(LangCode, this.ddlYear.SelectedValue.ToString(), this.ddlMonth.SelectedValue.ToString(), StationID);
            Hashtable hTable = GetHashTableData(hdnValues.Value.ToString());
            //check whether other updataed or no any other updataed this
            if (!CheckUpdataByOther(dt, hTable))
            {
                string strMsg = this.GetMessage("SOM_RecordOnceUpdataed");
                Alert(strMsg);
                CleanHiddenControlValues();
                GetScoreTable();
                BindDataTable();
                GetCleanPassScore();
                this.lblCleanScoreHeader.Text = this.ddlStation.SelectedItem.Text + " " + this.ddlYear.SelectedItem.Text + "/" + this.ddlMonth.SelectedItem.Text;
                return;
            }
            
            #endregion

            #region  Save Clean Shift Comments

            Hashtable hCommentTable = GetHashTableData(hdnCleanShiftComments.Value.ToString ());          
            #endregion

            #region  Save Lower Than Standard Reason
                Hashtable hLowerReasonTable = GetHashTableData(hdnLowerthanStandardReason.Value.ToString());
                Hashtable hLowerActionTable = GetHashTableData(this .hdnLowerthanStandardAction .Value .ToString ()); 
                int CleanID=0;
                if (dt.Rows.Count > 0)
                {
                   CleanID = int.Parse(dt.Rows[0]["CleanID"].ToString());
                }
                //Page.RegisterStartupScript("CheckHaveValues", "<script language='javascript'> ('" + this.UCFirePortection1.LastControlID + "');</script>");
             BLL.SOM.Event.StationCleaning.SaveCleanRelated(this.LangCode,
                                                               hTable,
                                                               hCommentTable,
                                                               hLowerReasonTable,
                                                               hLowerActionTable,
                                                               CleanID,
                                                               this.ddlYear.SelectedValue.ToString().Trim(),
                                                               this.ddlMonth.SelectedValue.ToString().Trim(),
                                                               StationID,
                                                               int.Parse(this.txtLeave.Text.ToString()),
                                                               int.Parse(this.txtFaultDay.Text.ToString()),
                                                               this.ODMUser.ID,
                                                               DAL.COM.Util.GetCurrentSystemTime(),
                                                               this.ODMUser.ID,
                                                               int.Parse(this.hdnCleanPassScore.Value.ToString())
                                                               ); 
            CleanHiddenControlValues();
            #endregion

            GetScoreTable();
            BindDataTable();
            AddRows();
            
            SetCleanID();// Add by zengshunbo issue:1047

            Alert(GetMessage("COM_UpdateResultSuccessfully"));

            if (this.hdnControlArrowStatus.Value == "false")//Add by jensen 2008-12-18
            {
                this.NumericUpDownExtender1.Enabled = false;
                this.NumericUpDownExtender2.Enabled = false;

                //--------------Add by zengshunbo 2009-03-18 issue:1102-------------
                this.btnLeaveDown.Disabled = true;
                this.btnLeaveUp.Disabled = true;
                this.btnFaultDayDown.Disabled = true;
                this.btnFaultDayUp.Disabled = true;
                //--------------End Add by zengshunbo 2009-03-18 issue:1102-------------
            }//Added end            

            this.ClientScript.RegisterStartupScript(typeof(BasePage), "OpenDepartPage", "<script language='javascript'>CheckIfAllScoreInput()</script>");

        }       

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            CleanHiddenControlValues();
            GetScoreTable();
            BindDataTable();
            GetCleanPassScore();
            this.lblCleanScoreHeader.Text = this.ddlStation.SelectedItem.Text + " " + this.ddlYear.SelectedItem.Text + "/" + this.ddlMonth.SelectedItem.Text;
        }

        private void CleanHiddenControlValues()
        {
            hdnValues.Value = "";
            hdnLowerthanStandardReason.Value = "";
            hdnLowerthanStandardAction.Value = "";
            hdnCleanShiftComments.Value = "";
            hdnScore.Value = "";
            hdnScoreID.Value = "";
        }

        protected void btnAddRow_ServerClick(object sender, EventArgs e)
        {
            GetScoreTable();       
            BindDataTable();            
            AddRows();
            //this.btnSave.Attributes.Add("onclick", "return CheckReasonAndActionInput();"); //Modify by zengshunbo 20090225 issue 1027
        }

        protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            CleanHiddenControlValues();
            GetScoreTable();
            BindDataTable();
            this.lblCleanScoreHeader.Text = this.ddlStation.SelectedItem.Text + " " + this.ddlYear.SelectedItem.Text + "/" + this.ddlMonth.SelectedItem.Text;
        }

        protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.FindByValueAndSelect(ddlMonth, "1");
            CleanHiddenControlValues();
            GetScoreTable();
            BindDataTable();
            this.lblCleanScoreHeader.Text =this.ddlStation .SelectedItem .Text+" "+ this.ddlYear.SelectedItem.Text + "/" + this.ddlMonth.SelectedItem.Text;
        }

        protected void ddlStation_SelectedIndexChanged(object sender, EventArgs e)
        {

            CleanHiddenControlValues();
            GetScoreTable();
            BindDataTable();
            GetCleanPassScore();
            this.lblCleanScoreHeader.Text = this.ddlStation.SelectedItem.Text + " " + this.ddlYear.SelectedItem.Text + "/" + this.ddlMonth.SelectedItem.Text;

        }

        protected void btnExportCurrentStationData_Click(object sender, EventArgs e)
        {
            //update by gordon 20151020 U247 Can not test
            //if (this.ddlStation.Items.FindByValue(this.ODMUser.StationID.ToString()) != null)
            //{
            //    DataSet dst = MTRC.ODMS.DAL.SOM.CodeSetup.CDCleanShift.GetExportData(Convert.ToInt32(this.LangCode), this.ODMUser.StationID, this.ddlYear.SelectedValue, this.ddlMonth.SelectedValue, this.ddlYear.SelectedValue, this.ddlMonth.SelectedValue);
            //    SetExportDataLanguage(ref dst);
            //    Common.ExportExcel(dst, Context, "StationCleaningData.xls");
            //}
            if (this.ddlStation.Items.FindByValue(this.ODMUser.LocationID.ToString()) != null)
            {
                DataSet dst = MTRC.ODMS.DAL.SOM.CodeSetup.CDCleanShift.GetExportData(Convert.ToInt32(this.LangCode), this.ODMUser.LocationID, this.ddlYear.SelectedValue, this.ddlMonth.SelectedValue, this.ddlYear.SelectedValue, this.ddlMonth.SelectedValue);
                SetExportDataLanguage(ref dst);
                Common.ExportExcel(dst, Context, "StationCleaningData.xls");
            }
        }

        protected void btnExportAllStationData_Click(object sender, EventArgs e)
        {
            DataSet dst = MTRC.ODMS.DAL.SOM.CodeSetup.CDCleanShift.GetExportData(Convert.ToInt32(this.LangCode), -1, this.ddlYear.SelectedValue, this.ddlMonth.SelectedValue, this.ddlYear.SelectedValue, this.ddlMonth.SelectedValue);
            SetExportDataLanguage(ref dst);
            Common.ExportExcel(dst, Context, "StationCleaningData.xls");
        }


        private void SetExportDataLanguage(ref DataSet dst)
        {
            dst.Tables[0].Columns["Station"].ColumnName = this.GetLabel("SOM_Station", this.LangCode);
            dst.Tables[0].Columns["YearMonth"].ColumnName = this.GetLabel("SOM_CleanYearMonth", this.LangCode);
            dst.Tables[0].Columns["NoOfWorkInjury"].ColumnName = this.GetLabel("SOM_NoOfWorkInjury", this.LangCode);
            dst.Tables[0].Columns["NoOfMachineDefective"].ColumnName = this.GetLabel("SOM_NoOfMachineDefective", this.LangCode);
            dst.Tables[0].Columns["Clean Shift (Comments)"].ColumnName = this.GetLabel("SOM_CleanShiftComments", this.LangCode);
            dst.Tables[0].Columns["Comments"].ColumnName = this.GetLabel("COM_GerneralComments", this.LangCode);
            dst.Tables[0].Columns["Clean Shift (Detail)"].ColumnName = this.GetLabel("SOM_CleanShiftDetail", this.LangCode);
            dst.Tables[0].Columns["WEEK_NO"].ColumnName = this.GetLabel("SOM_WeekNo", this.LangCode);
            dst.Tables[0].Columns["CleaningScore"].ColumnName = this.GetLabel("SOM_CleanScore", this.LangCode);
            dst.Tables[0].Columns["FlagBelowStandard"].ColumnName = this.GetLabel("SOM_FlagBelowStandard", this.LangCode);
            dst.Tables[0].Columns["SubstandardCause"].ColumnName = this.GetLabel("SOM_LowerStandardReason", this.LangCode);
            dst.Tables[0].Columns["SubstandardAction"].ColumnName = this.GetLabel("SOM_SubStandardAction", this.LangCode);
        }
    }
}
